package com.treeroot.springbootwithelastic.com.treeroot.es.tools;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author treeroot
 * es索引工具类包
 * (elasticsearch-7.17.11.jar)
 */
@Slf4j
@Component
public class IndexAction {

    @Value("${esconfig.userIndex}")
    private String userIndex;
    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * 1.创建索引创建对象，设置索引名.确认索引存在
     *
     * @param index 索引名
     * @return boolean
     * @throws IOException 异常
     */
    public boolean createIndex(String index) throws IOException {
        return restHighLevelClient.indices().create(new CreateIndexRequest(index), RequestOptions.DEFAULT).isAcknowledged();
    }
    /**
     * get指定索引
     *
     * @param index 索引名
     */
    public GetIndexRequest getIndex(String index) {
        return new GetIndexRequest(index);
    }

    /**
     * 查询指定索引是否存在
     *
     * @param index 索引名
     */
    public boolean existsIndex(String index) throws IOException {
        return restHighLevelClient.indices().exists(getIndex(index), RequestOptions.DEFAULT);
    }

    /**
     * 删除指定索引
     * 1.创建索引删除对象,设置索引名2.确认索引存在
     *
     * @param index 索引名
     */
    public boolean deleteIndex(String index) throws IOException {
        return restHighLevelClient.indices().delete(new DeleteIndexRequest(index), RequestOptions.DEFAULT).isAcknowledged();
    }

    /**
     * 创建索引指令
     *
     * @param index 索引名
     * @throws IOException 异常
     */
    public void createIndexCmd(String index) throws IOException {
        if (existsIndex(index)) {
            log.info("索引{}已经建立", index);
        } else {
            if (createIndex(index)) {
                log.info("创建{}索引成功", index);
            } else {
                log.error("创建索引失败");
                System.exit(0);
            }
        }
    }

}
